from sakucrm import models
from stack.service.stack import StackConfig
from stack.service.stack import get_choice_text
from stack.service.stack import Option
from django import forms
from django.shortcuts import HttpResponse
from django.shortcuts import redirect
from django.conf import settings
from django.db import transaction
from django.urls import path
from django.forms import modelformset_factory
from django.shortcuts import render


class StudentRecordModelForm(forms.ModelForm):
    '''

    '''
    class Meta:
        model=models.StudyRecord
        fields=['student','record','score','homework_note']

class StudyRecordConfig(StackConfig):
    '''
    每个学生的学习记录
    '''

    def get_urls(self):
        '''
        重写获得url的方法
        :return:
        '''
        urlpatterns = [
            path('list/', self.wrapper(self.list_view), name=self.get_list_url_name),
        ]
        return urlpatterns

    def list_view(self,request):
        '''
        重写view 方法
        :param request:
        :return:
        '''
        ccid=request.GET.get('ccid')
        modelformset_cls=modelformset_factory(models.StudyRecord,StudentRecordModelForm,extra=0)
        queryset=models.StudyRecord.objects.filter(course_record_id=ccid)
        if request.method=='GET':
            formset=modelformset_cls(queryset=queryset)
            return render(request,'studyrecord.html',{'formset':formset})
        if request.method=='POST':
            formset=modelformset_cls(data=request.POST)
            if formset.is_valid():
                formset.save()
                return redirect('/stack/sakucrm/studyrecord/list/?ccid=%s' %ccid)
            else:
                render(request,'studyrecord.html',{'formset':formset})